$(function() {

    function init() {
        // 获取数据
        $.post('/docRelease/get', { docId: getQueryString("docId"), versionNo: getQueryString("verNo") }, function(data, textStatus, xhr) {
            if (data && data.retCode == 0) {
                $("#title").html(data.retVal.name);
                $("#bMiddle").html(data.retVal.htmlDetail);
                $("#versionNO").html(data.retVal.versionNo);
                $("#historyBtn").attr("doc-id", data.retVal.docId);
            }
            createMenu();
        });

    }

    init();

    /**
     * 生成目录菜单
     */
    function createMenu() {
        var toc = new Array();
        $("#bMiddle :header").each(function(index, el) {
            var h = new Object();
            h["text"] = this.innerText;
            h["level"] = this.nodeName.replace("H", "");
            toc.push(h);
        });;
        container = $(".c-nvg");
        markdownToCRenderer(toc, container, 1);
        //tocDropdownMenu("", "目录");

        // 添加树形菜单折叠图标
        $('.c-nvg a').each(function() {
            var submenu = $(this).siblings('ul');
            if (submenu.length && submenu.children('li').length) {
                $(this).before('<span name="unfold" class="glyphicon glyphicon-menu-down" aria-hidden="true"></span> ');
            }
        });
    }

    /**
     * 导航树形图标点击事件
     */
    $('.c-nvg').on('click', 'span[name="unfold"]', function(e) {
        var self = $(this);
        if (self.hasClass('glyphicon-menu-right')) {
            self.removeClass('glyphicon-menu-right');
            self.addClass('glyphicon-menu-down');
        } else {
            self.removeClass('glyphicon-menu-down');
            self.addClass('glyphicon-menu-right');
        }
        var submenu = self.siblings('ul');
        if (submenu.length >=1) {
            submenu.toggle();
            // 不取消默认事件
            //e.preventDefault();
        }
    });


    /**
     *
     * 生成TOC(Table of Contents)
     * Creating ToC (Table of Contents)
     * 
     * @param   {Array}    toc             从marked获取的TOC数组列表
     * @param   {Element}  container       插入TOC的容器元素
     * @param   {Integer}  startLevel      Hx 起始层级
     * @returns {Object}   tocContainer    返回ToC列表容器层的jQuery对象元素
     */
    function markdownToCRenderer(toc, container, startLevel) {

        var html = "";
        var lastLevel = 0;
        var classPrefix = 'editormd-';

        startLevel = startLevel || 1;

        for (var i = 0, len = toc.length; i < len; i++) {
            var text = toc[i].text;
            var level = toc[i].level;

            if (level < startLevel) {
                continue;
            }

            if (level > lastLevel) {
                html += "";
            } else if (level < lastLevel) {
                html += (new Array(lastLevel - level + 2)).join("</ul></li>");
            } else {
                html += "</ul></li>";
            }

            html += "<li><a class=\"toc-level-" + level + "\" href=\"#" + text + "\" level=\"" + level + "\">" + text + "</a><ul>";
            lastLevel = level;
        }

        var tocContainer = container.find(".markdown-toc");

        if (tocContainer.length < 1) {
            var tocHTML = "<div class=\"markdown-toc " + classPrefix + "markdown-toc\"></div>";

            tocHTML = "<div class=\"" + classPrefix + "toc-menu\">" + tocHTML + "</div>";

            container.html(tocHTML);

            tocContainer = container.find(".markdown-toc");
        }

        tocContainer.html("<ul class=\"markdown-toc-list\"></ul>").children(".markdown-toc-list").html(html.replace(/\r?\n?\<ul\>\<\/ul\>/g, ""));

        return tocContainer;
    };

    /**
     *
     * 生成TOC下拉菜单
     * Creating ToC dropdown menu
     * 
     * @param   {Object}   container       插入TOC的容器jQuery对象元素
     * @param   {String}   tocTitle        ToC title
     * @returns {Object}                   return toc-menu object
     */
    function tocDropdownMenu(container, tocTitle) {

        tocTitle = tocTitle || "Table of Contents";

        var zindex = 400;
        // var tocMenus = container.find("." + this.classPrefix + "toc-menu");
        var tocMenus = $(".editormd-toc-menu");

        tocMenus.each(function() {
            var $this = $(this);
            var toc = $this.children(".markdown-toc");
            var icon = "<i class=\"fa fa-angle-down\"></i>";
            var btn = "<a href=\"javascript:;\" class=\"toc-menu-btn\">" + icon + tocTitle + "</a>";
            var menu = toc.children("ul");
            var list = menu.find("li");

            toc.append(btn);

            list.first().before("<li><h1>" + tocTitle + " " + icon + "</h1></li>");

            $this.mouseover(function() {
                menu.show();

                list.each(function() {
                    var li = $(this);
                    var ul = li.children("ul");

                    if (ul.html() === "") {
                        ul.remove();
                    }

                    if (ul.length > 0 && ul.html() !== "") {
                        var firstA = li.children("a").first();

                        if (firstA.children(".fa").length < 1) {
                            firstA.append($(icon).css({ float: "right", paddingTop: "4px" }));
                        }
                    }

                    li.mouseover(function() {
                        ul.css("z-index", zindex).show();
                        zindex += 1;
                    }).mouseleave(function() {
                        ul.hide();
                    });
                });
            }).mouseleave(function() {
                menu.hide();
            });
        });

        return tocMenus;
    };

    $("#historyBtn").click(function(event) {
        var self = $(this);
        var flag = 'false' == self.attr("data-cache") ? false : true;
        if (!flag) {
            $.post('/docRelease/history', { docId: self.attr("doc-id") }, function(data, textStatus, xhr) {
                if (data && data.retCode == 0) {
                    var docList = data.retVal;
                    if (null != docList) {
                        docList.forEach(function(item, index) {
                            $("#hisUl").append("<li><a href='#'>" + item.versionNo + "</a></li>");
                            $("#hisUl").data(item.versionNo, item);
                        });
                    }
                    self.attr("data-cache", true);
                }
            });
        }
    });

    $("#hisUl").on('click', 'a', function(event) {
        var $this = $(this);
        var doc = $("#hisUl").data($this.text());
        $("#title").html(doc.name);
        $("#bMiddle").html(doc.htmlDetail);
        $("#versionNO").html(doc.versionNo);
        createMenu();
    });


});